package que.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import que.app.AppV1;
import que.common.Word;
import que.util.AtguiguUtil;
import que.util.FlinkSinkUtil;

import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * @author Naruto
 * @description: 独立观看人数
 * @Class_Name que.app.dwd.log.DwdTrafficUniqueViewerDetail
 * @Date 2022/09/01 17:59
 */
public class DwdTrafficUniqueViewerDetail extends AppV1 {

    public static void main(String[] args) {
        new DwdTrafficUniqueViewerDetail().init(
                9005,
                2,
                "DwdTrafficUniqueViewerDetail",
                Word.TOPIC_DWD_TRAFFIC_VIDEO
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((json,ts) ->json.getLong("ts"))
                )
                .keyBy(json -> json.getJSONObject("common").getString("uid")+"_"+json.getJSONObject("appVideo").getString("video_id"))
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(
                        new ProcessWindowFunction<JSONObject, String, String, TimeWindow>() {

                            private ValueState<String> viewDate;//记录上次观看日期

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                viewDate = getRuntimeContext().getState(
                                        new ValueStateDescriptor<String>("viewDate", String.class)
                                );
                            }

                            @Override
                            public void process(String key,
                                                Context ctx,
                                                Iterable<JSONObject> it,
                                                Collector<String> out) throws Exception {

                                String today = AtguiguUtil.toDate(ctx.window().getStart());
                                //上次观看时间
                                String lastDay = viewDate.value();
                                System.out.println("11111111111111111");
                                if (!today.equals(lastDay)) {
                                    List<JSONObject> list = AtguiguUtil.toList(it);
                                    System.out.println(today);
                                    //取出时间最小的数据
                                    JSONObject min =Collections.min(list,(o1,o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));

                                    out.collect(min.toJSONString());
                                    viewDate.update(today);//更新日期
                                }

                            }

                        }
                )
//                .print();
                .addSink(FlinkSinkUtil.getKafkaSink(Word.TOPIC_DWD_TRAFFIC_UqViewer));
    }


}
